package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //1. 校验参数 文章id必须传
        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        // 获取用户id\
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
        if (user == null) {
            //说明是游客模式
            return yudu(apBehaviorEntry,dto,null);
        }

        Integer userId = user.getId();
        return yudu(apBehaviorEntry,dto,userId);

//        throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE,"同时缺少用户和设备ID");

    }

    private ResponseResult yudu(ApBehaviorEntry apBehaviorEntry, ReadBehaviorDTO dto,Integer userId) {
        apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "获取行为实体信息失败");
        }
        //3. 判断阅读行为是否存在
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior apReadBehavior = new ApReadBehavior();
        apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        //5. 不存在  创建阅读行为 并初始化count字段值为 1
        if (apReadBehavior == null) {
            apReadBehavior = new ApReadBehavior();
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount((short)1);
            mongoTemplate.insert(apReadBehavior);
            return ResponseResult.okResult("阅读更新完成1");

        }
        //4. 存在  将阅读行为的count字段加1 并修改
        short count=(short)(apReadBehavior.getCount()+1);
        apReadBehavior.setCount(count);
        mongoTemplate.save(apReadBehavior);
        // =======================新加代码==========================
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("阅读行为 发送消息 ==>{}",mess);
        // =======================新加代码==========================
        return ResponseResult.okResult("阅读更新完成"+count);
    }

}
